package com.sunjy.common.utils;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * RSA安全编码组件
 * 
 * @version 1.0
 */
public abstract class RSACoder {
	private static final Logger LOGGER = LoggerFactory.getLogger(RSACoder.class);
	
	/**
	 * 数字签名
	 * 密钥算法
	 */
	public static final String KEY_ALGORITHM = "RSA";

	/**
	 * 数字签名
	 * 签名/验证算法
	 */
	public static final String SIGNATURE_ALGORITHM = "SHA1withRSA";

	/**
	 * 公钥
	 */
	private static final String PUBLIC_KEY = "RSAPublicKey";

	/**
	 * 私钥
	 */
	private static final String PRIVATE_KEY = "RSAPrivateKey";

	/**
	 * RSA密钥长度 默认1024位，
	 *  密钥长度必须是64的倍数， 
	 *  范围在512至65536位之间。
	 */
	private static final int KEY_SIZE = 1024;
	 /** *//** 
     * RSA最大加密明文大小 
     */  
    private static final int MAX_ENCRYPT_BLOCK = 117;  
      
    /** *//** 
     * RSA最大解密密文大小 
     */  
    private static final int MAX_DECRYPT_BLOCK = 128;  

	/**
	 * 签名(参数是字节格式)
	 * 
	 * @param data
	 *            待签名数据
	 * @param privateKey
	 *            私钥
	 * @return byte[] 数字签名
	 * @throws Exception
	 */
	public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {

		// 转换私钥材料
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

		// 实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

		// 取私钥匙对象
		PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 实例化Signature
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

		// 初始化Signature
		signature.initSign(priKey);

		// 更新
		signature.update(data);

		// 签名
		return signature.sign();
	}

	/**
	 * 签名（参数是字符串格式，返回签名字符串base64格式）
	 * @param content：待签名的字符串
	 * @param privateKey：私钥(以Base64编码后传入)
	 * @return：成功时返回base64编码的签名串；失败时null
	 */
	public static String sign(String content, String privateKey){
		String result = null;
		String charset = "UTF-8";
		
		byte[] signed = null;
		
		try{
			signed = sign(content.getBytes(charset),Base64.decode(privateKey));
			result = Base64.encode(signed);
		}catch(Exception ex){
			LOGGER.error("sign exception.content={}, exp={}",content,ex);
		}
		
		return result;
	}
	
	/**
	 * 公钥验证签名（输入参数是字节格式）
	 * 
	 * @param data
	 *            待校验数据
	 * @param publicKey
	 *            公钥
	 * @param sign
	 *            数字签名
	 * 
	 * @return boolean 校验成功返回true 失败返回false
	 * @throws Exception
	 * 
	 */
	public static boolean verify(byte[] data, byte[] publicKey, byte[] sign)
			throws Exception {

		// 转换公钥材料
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

		// 实例化密钥工厂
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

		// 生成公钥
		PublicKey pubKey = keyFactory.generatePublic(keySpec);

		// 实例化Signature
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

		// 初始化Signature
		signature.initVerify(pubKey);

		// 更新
		signature.update(data);

		// 验证
		return signature.verify(sign);
	}

	/**
	 * 公钥验证签名（输入参数是字符串格式）
	 * @param content：待校验数据
	 * @param sign：签名串
	 * @param publicKey：公钥(公钥以Base64编码后传入)
	 * @return true：成功；false：失败
	 */
	public static boolean verify(String content,String sign,String publicKey) throws Exception {
		boolean result = false;
		
		byte[] data = content.getBytes("utf-8");
		byte[] encodedKey = Base64.decode(publicKey);
		byte[] signed = Base64.decode(sign);
		
		try{
			result = verify(data,encodedKey,signed);
		}catch(Exception ex){
			LOGGER.error("verify signature exception.content={},sign={}, exp={}",content,sign,ex);
		}
		
		return result;
	}
	
	/**
	 * 公钥加密
	 * @param content：待加密字符串
	 * @param publicKey：公钥(以Base64编码后传入)
	 * @return: 加密成功时返回Base64编码的加密串，失败时返回null
	 */
	public static String encryptByPublicKey(String content,String publicKey){
		String result = null;
		
		byte[] decodedKey = Base64.decode(publicKey);
		
		byte[] encrytedData = null;
		
		try{
			byte[] data = content.getBytes("utf-8");
			encrytedData = encryptByPublicKey(data,decodedKey);
			result = new String(Base64.encode(encrytedData));
		}
		catch(Exception ex){
			LOGGER.error("encryptByPublicKey exception.content={}, exp={}",content,ex);
		}
		
		return result;
	}
	
	

	/**
	 * 私钥解密
	 * @param content：待解密的字符串，Base64编码格式
	 * @param privateKey：私钥，Base64编码格式
	 * @return：成功时返回解密后的明文，失败时null
	 */
	public static String decryptByPrivateKey(String content, String privateKey){
		String result = null;
		
		byte[] data = Base64.decode(content);
		byte[] key = Base64.decode(privateKey);
		
		
		byte[] decryt = null;
		
		try{
			decryt = decryptByPrivateKey(data,key);
			result = new String(decryt, "utf-8");
		}catch(Exception ex){
			LOGGER.error("decryptByPrivateKey exception.content={}, exp={}",content,ex);
		}
		
		return result;
	}
	
	
	/**
	 * 公钥加密
	 * 
	 * @param data
	 *            待加密数据
	 * @param key
	 *            公钥
	 * @return byte[] 加密数据
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, byte[] key)
			throws Exception {

		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);

		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

		PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);

		// 对数据加密
		Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");//keyFactory.getAlgorithm());

		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		
		return shardingEntrypt(cipher,data);
	}
	
	
	/**
	 * 私钥解密
	 * 
	 * @param data
	 *            待解密数据
	 * @param key
	 *            私钥
	 * @return byte[] 解密数据
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
			throws Exception {

		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);

		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);

		// 生成私钥
		PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());

		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		return shardingDecrypt(cipher,data);
	}
	/**
	 * 取得私钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	public static byte[] getPrivateKey(Map<String, Object> keyMap)
			throws Exception {

		Key key = (Key) keyMap.get(PRIVATE_KEY);

		return key.getEncoded();
	}

	/**
	 * 取得公钥
	 * 
	 * @param keyMap
	 * @return
	 * @throws Exception
	 */
	public static byte[] getPublicKey(Map<String, Object> keyMap)
			throws Exception {

		Key key = (Key) keyMap.get(PUBLIC_KEY);

		return key.getEncoded();
	}
	
	
	private static byte[] shardingEntrypt(Cipher cipher, byte[] data) throws Exception {
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_ENCRYPT_BLOCK;
			}
		} finally {
			out.close();
		}
		
		return out.toByteArray();  

	}
	private static byte[] shardingDecrypt(Cipher cipher, byte[] data) throws Exception {
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		try {
			int offSet = 0;
			byte[] cache;
			int i = 0;
			// 对数据分段加密
			while (inputLen - offSet > 0) {
				if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
					cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
				} else {
					cache = cipher.doFinal(data, offSet, inputLen - offSet);
				}
				out.write(cache, 0, cache.length);
				i++;
				offSet = i * MAX_DECRYPT_BLOCK;
			}
		} finally {
			out.close();
		}
		
		return out.toByteArray();  
		
	}

	

	/**
	 * 初始化密钥
	 * 
	 * @return Map 密钥对儿 Map
	 * @throws Exception
	 */
	public static Map<String, Object> initKey() throws Exception {

		// 实例化密钥对儿生成器
		KeyPairGenerator keyPairGen = KeyPairGenerator
				.getInstance(KEY_ALGORITHM);

		// 初始化密钥对儿生成器
		keyPairGen.initialize(KEY_SIZE);

		// 生成密钥对儿
		KeyPair keyPair = keyPairGen.generateKeyPair();

		// 公钥
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		

		// 私钥
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

		// 封装密钥
		Map<String, Object> keyMap = new HashMap<String, Object>(2);

		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);

		return keyMap;
	}

	public static void main(String[] args) {
		String str= "测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密测试中文加密-954872223";
      String privatekey= "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMkwOyyarMoCEcyZKo6cY8kCcQIJHBv2nn64L5/v/cNAp5gpj9kIvdrimgt7H4bYg/RQCR+kVEaWqNcdu1mJxVZpUZHPbxs+nliaIe3e0Y50ff4RoLjsA9fj+zSRa0m8j4nZxv+DNiKCsax3heqLEszoa5rvd+WVjALAdYYUKXFLAgMBAAECgYBhCOMxgzSdhdwB20n8WI+ELqpEuhIVpqARLFLECCNTngZ3TGx12FKBlNOJgAvXpOwX1NZhrYd8OEQc5NksuVc0mBEZCi1xvRV1DNe23mCZp5Qq4kWPd+o5ymPx272RKjvB2A+WoUcseriV10qbVVs8wxqDhnwrrA6KLxqxkYzIwQJBAO4oKglqc0GQX5ZuObhea9tcihzePe5CG+c/qGZPx/p3I/I+XW/4K/dpk6zysQONwHlwdPL7lZI55ZbXk5nqMeECQQDYQwNu6wYPzVV2LsL6iIxtAkz0v3xlh/26xt4sQxyOIg0oUmestfehU5Oc7w/WEzNWkYyPQeS7eSH7/QoqPiCrAkEAm6FdjxekR+Ubwgc36vaxDwGTM7g7ylYjO+QKnQlnypJOyD/e+Yu4146DtZJHAOaCMBnAIwUrQgpZsVAhIYS8oQJAVLDBqnFNmWifHD4pyzUoURRCkOJgU96Sxc9VeF3708mP/4dt5FwKktoJB78zI3G3fCJZukxix+wjG+y3S12zKwJBANcLQZdGW8ogdvK/71VFuKl18EUHHrPQJRGdVfdm5RXsP0mk+d6tq7mv0f0aHD9Gmze6hL4w5QTG6eoc5cVhehg=";
      String pubkey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJMDssmqzKAhHMmSqOnGPJAnECCRwb9p5+uC+f7/3DQKeYKY/ZCL3a4poLex+G2IP0UAkfpFRGlqjXHbtZicVWaVGRz28bPp5YmiHt3tGOdH3+EaC47APX4/s0kWtJvI+J2cb/gzYigrGsd4XqixLM6Gua73fllYwCwHWGFClxSwIDAQAB";
		
		try {
			String encrypt = encryptByPublicKey(str, pubkey);
			System.out.println(encrypt);
				System.out.println(decryptByPrivateKey("pIvhWbiNtb1b3eqfldZ+QDb0ojP2dC6lpXW4MN5SqmI94O29MXIMVEwnGTlZysDagPaknrfSsUKloWmKXw+lM8EayvLjcfkxAD0IExG8PlpWaIScsRCDP7hgBBH1tzXEz3jT9OtyzUkBrmzXcnwH6Jmfgl3stvVtN+1xxo2SmM0=", privatekey));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		
	}
}
